package com.hjb.service.config.rest;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

/**
* @ClassName: RestClient
* @Description: TODO(这里用一句话描述这个类的作用)
* @author <a href="mailto:125671254@qq.com">Pan Xinwen</a>
* @date 2017年4月23日 下午12:11:42
 */
@Component
public class RestClient {
	  private static Logger logger = LoggerFactory.getLogger(RestClient.class);
	  @Autowired
	  private RestTemplate restTemplate;

	  public <T> T post(String url, Map<String, Object> param, Class<T> responseType) throws HttpServerErrorException {
		logger.info("调用地址："+url);  
		MultiValueMap<String, String> requestEntity = new LinkedMultiValueMap<>();
	    param.keySet().stream().forEach(key -> requestEntity.add(key, String.valueOf(param.get(key))));
	    return restTemplate.postForObject(url, requestEntity, responseType);
	  }

	  public <T> T get(String url,Map<String,Object> param,Class<T> responseType)  throws HttpServerErrorException{
		logger.info("调用地址："+url);
	    return restTemplate.getForObject(url,responseType,param);
	  }
	  public <T> T post(String url, String json, Class<T> responseType) throws HttpServerErrorException {
		  logger.info("调用地址："+url);  
		  HttpHeaders headers = new HttpHeaders();
	      MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
	      headers.setContentType(type);
	      headers.add("Accept", MediaType.APPLICATION_JSON.toString());
	      HttpEntity<String> formEntity = new HttpEntity<String>(json, headers);
	      return restTemplate.postForObject(url, formEntity,responseType);
	      
	  }
	  
}
